package v3.chapter2.syn_Out_asyn;

import java.util.ArrayList;
import java.util.List; 
 

public class Run {

	public static void main(String[] args) {
		MyList service=new MyList();
		MyThread1 a=new MyThread1(service);
		a.setName("A");
		a.start();
		
		MyThread2 b=new MyThread2(service);
		b.setName("B");
		b.start();
	}

}


class MyThread1 extends Thread {

	private MyList service;

	public MyThread1(MyList service) {
		super();
		this.service = service;
	}

	@Override
	public void run() {
		for(int i=0;i<100000;i++) {
			service.add("threadA"+(i+1));
		}
		
	}

}

class MyThread2 extends Thread {

	private MyList service;

	public MyThread2(MyList service) {
		super();
		this.service = service;
	}

	@Override
	public void run() {
		for(int i=0;i<100000;i++) {
			service.add("threadB"+(i+1));
		}
		
		
	}

} 


class MyList{
	private List list=new ArrayList();
	synchronized public void add(String username) {
		System.out.println("ThreadName="+Thread.currentThread().getName()+" 执行了 add 方法！");
		list.add(username);
		System.out.println("ThreadName="+Thread.currentThread().getName()+" 退出了 add 方法！");
	}
	
	synchronized public int getSize() {
		System.out.println("ThreadName="+Thread.currentThread().getName()+" 执行了 getSize 方法！");
		int sizeValue=list.size();
		System.out.println("ThreadName="+Thread.currentThread().getName()+" 退出了 getSize 方法！");
		return sizeValue;
	}
}